from fastapi import applications
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.openapi.utils import get_openapi

from rosa.scarborough_fair.generator_setting.settings import settings


def get_custom_contact():
    contact = dict()
    if settings.CONTACT_NAME:
        contact["name"] = settings.CONTACT_NAME
    if settings.CONTACT_URL:
        contact["url"] = settings.CONTACT_URL
    if settings.CONTACT_EMAIL:
        contact["email"] = settings.CONTACT_EMAIL

    if contact:
        return contact


def get_custom_license_info():
    license_info = dict()
    if settings.LICENSE_NAME:
        license_info["name"] = settings.LICENSE_NAME
    if settings.LICENSE_URL:
        license_info["url"] = settings.LICENSE_URL

    if license_info:
        return license_info


# ###################
# ###   定制界面   ###
# ##################
# 定制swagger界面元素
def get_swagger_ui_html_rewrite(*args, **kwargs):
    # 自定义元素
    if settings.SWAGGER_FAVICON_URL:
        kwargs["swagger_favicon_url"] = settings.SWAGGER_FAVICON_URL
    if settings.SWAGGER_JS_URL:
        kwargs["swagger_js_url"] = settings.SWAGGER_JS_URL
    if settings.SWAGGER_CSS_URL:
        kwargs["swagger_css_url"] = settings.SWAGGER_CSS_URL
    return get_swagger_ui_html(*args, **kwargs)


# 定制redoc界面元素
def get_redoc_html_rewrite(*args, **kwargs):
    # 自定义元素
    if settings.REDOC_FAVICON_RUL:
        kwargs["redoc_favicon_url"] = settings.REDOC_FAVICON_RUL
    if settings.REDOC_JS_RUL:
        kwargs["redoc_js_url"] = settings.REDOC_JS_RUL
    return get_redoc_html(*args, **kwargs)


# 自定义openapi显示
def custom_openapi(app):
    def wrapper():
        if app.openapi_schema:
            return app.openapi_schema
        openapi_schema = get_openapi(
            title=settings.SITE_TITLE,
            version=settings.DOCS_VERSION,
            openapi_version=app.openapi_version,
            description=settings.SITE_DESCRIPTION,
            routes=app.routes,
            terms_of_service=settings.TERMS_OF_SERVICE,
            contact=get_custom_contact(),
            license_info=get_custom_license_info(),
            tags=app.openapi_tags,
            servers=app.servers,
        )
        openapi_schema["info"]["x-logo"] = {
            "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
        }
        app.openapi_schema = openapi_schema
        return app.openapi_schema

    return wrapper


applications.get_swagger_ui_html = get_swagger_ui_html_rewrite
applications.get_redoc_html = get_redoc_html_rewrite

if settings.ENV == "product":
    openapi_url = None
    docs_url = None
    redoc_url = None
else:
    openapi_url = settings.OPENAPI_URL
    docs_url = settings.DOCS_URL
    redoc_url = settings.REDOC_URL
